//
//  ZSNAVPlayerView.swift
//  AgoraAVPlayerZhaosn
//
//  Created by zhaosuning on 2022/1/5.
//

import UIKit
import AVKit

typealias VideoItemPlayStartHandle = (_ videoView:ZSNAVPlayerView,_ itemIndex:Int) -> ()
typealias VideoItemPlayEndHandle = (_ videoView:ZSNAVPlayerView,_ itemIndex:Int) -> ()

class ZSNAVPlayerView: UIView
{
    var curPlayerLayer:AVPlayerLayer?
    var nextPlayerLayer:AVPlayerLayer?
    var curPlayer: AVPlayer?
    private var nextPlayer: AVPlayer?
    
    var videoUrls = [Bundle.main.url(forResource: "daojiangxing", withExtension: "mp3")!]
    var videoItemPlayStart:VideoItemPlayStartHandle?
    var videoItemPlayEnd:VideoItemPlayEndHandle?
    private var play_index:Int = 0
    var playIndex:Int {
        get {
            return play_index
        }
    }
    var curPlayerItem:AVPlayerItem?
    var nextPlayerItem:AVPlayerItem?
    
    
    fileprivate func setupPlayer(_ videoUrls:Array<URL>? = nil) {
        if videoUrls != nil {
            self.videoUrls = videoUrls!
        }
        curPlayerLayer = AVPlayerLayer()
        curPlayerLayer?.frame = CGRect.init(origin: .zero, size: self.frame.size)
        //self.layer.addSublayer(curPlayerLayer!)
    }
    
    fileprivate func playVideo(videoUrl:URL) {
        if curPlayerLayer == nil {
            setupPlayer()
        }
        else {
            curPlayerLayer?.removeFromSuperlayer()
        }
        if nextPlayerLayer != nil {
            self.layer.addSublayer(nextPlayerLayer!)
            let tempPlayerLayer = curPlayerLayer
            let tempPlayer = curPlayer
            let tempPlayerItem = curPlayerItem
            curPlayerLayer = nextPlayerLayer
            curPlayer = nextPlayer
            curPlayerItem = nextPlayerItem
            nextPlayerLayer = tempPlayerLayer
            nextPlayer = tempPlayer
            nextPlayerItem = tempPlayerItem
//            curPlayerLayer?.player = curPlayer
        }
        else {
            if let item = curPlayerItem {
                NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item)
            }
            self.layer.addSublayer(curPlayerLayer!)
            let playerItem = AVPlayerItem(url: videoUrl)
            curPlayerItem = playerItem
            curPlayer = AVPlayer(playerItem: playerItem)
            curPlayerLayer?.player = curPlayer
            NotificationCenter.default.addObserver(self, selector: #selector(playFinish), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)
        }

        curPlayer?.play()
    }
    
    fileprivate func preloadVideo(videoUrl:URL) {
        if nextPlayerLayer == nil {
            nextPlayerLayer = AVPlayerLayer()
            nextPlayerLayer?.frame = CGRect.init(origin: .zero, size: self.frame.size)
        }
        if let item = nextPlayerItem {
            NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item)
        }
        let playerItem = AVPlayerItem(url: videoUrl)
        nextPlayerItem = playerItem
        nextPlayer = AVPlayer(playerItem: playerItem)
        nextPlayerLayer?.player = nextPlayer
        NotificationCenter.default.addObserver(self, selector: #selector(playFinish), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)
    }
    
    func playVideo(itemIndex:Int) {
        play_index = itemIndex
        playVideo(videoUrl: videoUrls[itemIndex])
        if let handle = videoItemPlayStart {
            handle(self,itemIndex)
        }
        var nextPlayIndex = self.playIndex + 1
        if nextPlayIndex > self.videoUrls.count - 1 {
            nextPlayIndex = 0
        }
        preloadVideo(videoUrl: videoUrls[nextPlayIndex])
    }
    
    func playNextVideo() {
        guard videoUrls.count > 0 else {
            return
        }
        var nextPlayIndex = self.playIndex + 1
        if nextPlayIndex > self.videoUrls.count - 1 {
            nextPlayIndex = 0
        }
        playVideo(itemIndex: nextPlayIndex)
    }
    
    func pausePlay(){
        curPlayer?.pause()
        curPlayer?.seek(to: CMTime.init(value: 0, timescale: 1))
    }
    
    func stopPlay() {
        curPlayer?.pause()
        curPlayer?.seek(to: CMTime.init(value: 0, timescale: 1))
        if curPlayerLayer != nil {
            curPlayerLayer?.removeFromSuperlayer()
            curPlayerLayer = nil
        }
        if nextPlayerLayer != nil {
            nextPlayerLayer?.removeFromSuperlayer()
            nextPlayerLayer = nil
        }
    }
    
    @objc fileprivate func playFinish() {
        if let handle = videoItemPlayEnd {
            handle(self,playIndex)
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

}
